package com.bobo.Socket;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
/**
 * TCP协议通信（UDP）
 * 客户端
 * @author win7
 *
 */
public class UDPClient {

	public static void main(String[] args) {
		try {
		//1.根据服务器主机名获取到服务器端的InetAddress
			InetAddress inetAddress = InetAddress.getByName("localhost");
			
		//2.创建数据包，包含发送的信息
			byte[] data="我是客户端".getBytes();
			DatagramPacket datagramPacket =new DatagramPacket(data, data.length, inetAddress, 8889);
			
		//3.创建DatagramSocket实例 用于发送信息给服务端
			DatagramSocket datagramSocket = new DatagramSocket();
			datagramSocket.send(datagramPacket);
			
		//接收服务器端发过来的消息
			byte[] result=new byte[1024];//定义信息长度
			DatagramPacket datagramPacket2=new DatagramPacket(result, result.length);//创建数据报接收存放消息
			datagramSocket.receive(datagramPacket2);//接收服务端发过来的消息
			System.out.println("这是客户端，收到服务器端返回的消息："+new String(datagramPacket2.getData(),0, datagramPacket2.getLength()));
			
		//关闭资源
			datagramSocket.close();
			
			
		} catch (Exception e) {
			// TODO: handle exception
		}
	}

}
